﻿using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlanDetail;
using ERP_SaaS_WinForm.生产计划_派单_车间;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERP_SaaS_WinForm.生产工单_报工_工序;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class ProductPlanMain : Form
    {
        private string urls;
       
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);

        public ProductPlanMain()
        {
            InitializeComponent();
            SetFormIcon();
            InitializeForm();
            urls = Apllo.ApiBaseUrl;
        }
        

        
        private void InitializeForm()
        {
            this.Text = "生产计划";
            this.Size = new Size(1600, 700); // 进一步增加窗体宽度以显示所有列
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.Sizable; // 改为可调整大小
            this.MaximizeBox = true; // 允许最大化
            this.MinimizeBox = true; // 允许最小化
            
            // 禁用DataGridView的列重新排序功能
            dgvPlanList.AllowUserToOrderColumns = false;
            
            // 设置DataGridView的Dock属性，使其能够适应窗体大小
            dgvPlanList.Dock = DockStyle.Fill;
            
            // 设置其他控件的Anchor属性，使其能够随窗体大小调整
            SetupControlAnchors();
            
            // 添加窗体大小改变事件
            this.SizeChanged += ProductPlanMain_SizeChanged;
        }
        
        /// <summary>
        /// 设置控件的Anchor属性，使其能够随窗体大小调整
        /// </summary>
        private void SetupControlAnchors()
        {
            // 设置TabControl的Dock属性
            skinTabControl1.Dock = DockStyle.Fill;
            
            // 设置TabPage的Dock属性
            skinTabPage1.Dock = DockStyle.Fill;
            
            // 设置搜索区域控件的Anchor属性
            if (lblProductCode != null) lblProductCode.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (txtProductCode != null) txtProductCode.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (lblProductName != null) lblProductName.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (txtProductName != null) txtProductName.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (lblProductResource != null) lblProductResource.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (cboProductResource != null) cboProductResource.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (lblProductState != null) lblProductState.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (cboProductState != null) cboProductState.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (btnReset != null) btnReset.Anchor = AnchorStyles.Top | AnchorStyles.Right;
            if (btnSearch != null) btnSearch.Anchor = AnchorStyles.Top | AnchorStyles.Right;
            
            // 设置分页控件的Anchor属性
            if (lblTotalCount != null) lblTotalCount.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (lblTotalPage != null) lblTotalPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnFirstPage != null) btnFirstPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnPreviousPage != null) btnPreviousPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnNextPage != null) btnNextPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnLastPage != null) btnLastPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (txtPageNumber != null) txtPageNumber.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnGoPage != null) btnGoPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
        }
        
        /// <summary>
        /// 窗体大小改变事件处理
        /// </summary>
        private void ProductPlanMain_SizeChanged(object sender, EventArgs e)
        {
            // 调整DataGridView的列宽以适应新的窗体宽度
            AdjustDataGridViewColumns();
            
            // 如果窗体最大化，进行特殊处理
            if (this.WindowState == FormWindowState.Maximized)
            {
                HandleMaximizedState();
            }
        }
        
        /// <summary>
        /// 处理窗体最大化状态
        /// </summary>
        private void HandleMaximizedState()
        {
            // 确保DataGridView充分利用可用空间
            if (dgvPlanList != null)
            {
                // 设置DataGridView的Dock属性为Fill，确保它填充整个可用空间
                dgvPlanList.Dock = DockStyle.Fill;
                
                // 调整列宽以充分利用最大化后的空间
                AdjustDataGridViewColumns();
                
                // 刷新DataGridView以确保正确显示
                dgvPlanList.Refresh();
            }
        }
        
        /// <summary>
        /// 调整DataGridView列宽以适应窗体大小
        /// </summary>
        private void AdjustDataGridViewColumns()
        {
            if (dgvPlanList != null && dgvPlanList.Columns.Count > 0)
            {
                // 计算可用宽度
                int availableWidth = dgvPlanList.Width - 20; // 减去滚动条宽度
                
                // 定义列的优先级和最小宽度
                var columnConfigs = new Dictionary<string, (int minWidth, int priority)>
                {
                    {"计划Id", (60, 1)},
                    {"订单编号", (80, 2)},
                    {"计划编号", (100, 3)},
                    {"计划名称", (120, 4)},
                    {"来源类型", (80, 5)},
                    {"产品名称", (120, 6)},
                    {"产品编号", (100, 7)},
                    {"规格型号", (100, 8)},
                    {"单位", (60, 9)},
                    {"计划数量", (80, 10)},
                    {"计划开工时间", (120, 11)},
                    {"计划完工时间", (120, 12)},
                    {"需求日期", (100, 13)},
                    {"状态", (80, 14)},
                    {"删除", (60, 15)},
                    {"修改", (60, 16)},
                    {"详情", (60, 17)}
                };
                
                // 计算所有列的最小宽度总和
                int totalMinWidth = 0;
                foreach (DataGridViewColumn column in dgvPlanList.Columns)
                {
                    if (columnConfigs.ContainsKey(column.HeaderText))
                    {
                        totalMinWidth += columnConfigs[column.HeaderText].minWidth;
                    }
                    else
                    {
                        totalMinWidth += 80; // 默认最小宽度
                    }
                }
                
                // 如果可用宽度小于最小宽度总和，启用水平滚动条
                if (availableWidth < totalMinWidth)
                {
                    dgvPlanList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                    
                    // 设置每列的固定宽度
                    foreach (DataGridViewColumn column in dgvPlanList.Columns)
                    {
                        if (columnConfigs.ContainsKey(column.HeaderText))
                        {
                            column.Width = columnConfigs[column.HeaderText].minWidth;
                            column.MinimumWidth = columnConfigs[column.HeaderText].minWidth;
                        }
                        else
                        {
                            column.Width = 80;
                            column.MinimumWidth = 80;
                        }
                    }
                }
                else
                {
                    // 有足够空间，使用自动调整
                    dgvPlanList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    
                    // 为特定列设置最小宽度
                    foreach (DataGridViewColumn column in dgvPlanList.Columns)
                    {
                        if (columnConfigs.ContainsKey(column.HeaderText))
                        {
                            column.MinimumWidth = columnConfigs[column.HeaderText].minWidth;
                        }
                        else
                        {
                            column.MinimumWidth = 80;
                        }
                    }
                    
                    // 强制重新计算列宽
                    dgvPlanList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                }
            }
        }
       
      

        /// <summary>
        /// 设置窗体图标
        /// </summary>
        private void SetFormIcon()
        {
            
                string[] possiblePaths = {
                    System.IO.Path.Combine(Application.StartupPath, "..", "..", "Images", "ww.ico")
                };

                string iconPath = possiblePaths.FirstOrDefault(System.IO.File.Exists);
                if (!string.IsNullOrEmpty(iconPath))
                {
                    this.Icon = new System.Drawing.Icon(iconPath);
                }
           
        }

        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            txtProductCode.Text= string.Empty;
            txtProductName.Text= string.Empty;
            if(cboProductResource.Items.Count>0)
            {
                cboProductResource.SelectedIndex = 0;
            }
            if(cboProductState.Items.Count>0)
            {
                cboProductState.SelectedIndex = 0; // 选择"请选择"项
            }
        }
        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("=== 开始执行搜索操作 ===");

                string planCode=txtProductCode.Text.Trim();
                string productName=txtProductName.Text.Trim(); // 修改：使用产品名称查询
                string resource = cboProductResource.SelectedValue?.ToString();
                string planState = cboProductState.SelectedValue?.ToString();

                var parameters = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(planCode)) parameters.Add("planCode", planCode);
                if (!string.IsNullOrEmpty(productName)) parameters.Add("productName", productName); // 修改：使用productName字段
                if (!string.IsNullOrEmpty(resource)) parameters.Add("resource", resource);
                if (!string.IsNullOrEmpty(planState)) parameters.Add("planState", planState);
                parameters.Add("pageIndex", pageIndex.ToString());
                parameters.Add("pageSize", pageSize.ToString());

                var apiResponse = await ApiRequestHelper.GetAsync<ApiResponse>("api/Plan/GetPlan", parameters);
                
                if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                {
                    var response = apiResponse.Data;
                    Console.WriteLine($"API调用成功，返回数据: {JsonConvert.SerializeObject(response.data)}");
                    Console.WriteLine($"API响应状态码: {response.code}");
                    Console.WriteLine($"API响应消息: {response.msg}");
                    Console.WriteLine($"API响应数据类型: {response.data?.GetType().Name}");
                    
                    // 确保数据是List<PlanData>类型
                    List<PlanData> planList = null;
                    if (response.data is List<PlanData>)
                    {
                        planList = response.data as List<PlanData>;
                        Console.WriteLine($"数据已经是List<PlanData>类型，数量: {planList?.Count ?? 0}");
                    }
                    else if (response.data != null)
                    {
                        // 如果不是正确的类型，尝试转换
                        planList = JsonConvert.DeserializeObject<List<PlanData>>(JsonConvert.SerializeObject(response.data));
                        Console.WriteLine($"数据转换后，数量: {planList?.Count ?? 0}");
                    }
                    else
                    {
                        Console.WriteLine("API返回的data为null");
                    }
                    
                    // 确保planList不为null
                    if (planList == null)
                    {
                        planList = new List<PlanData>();
                        Console.WriteLine("planList为null，创建空列表");
                    }
                    
                    Console.WriteLine($"最终设置到DataGridView的数据数量: {planList.Count}");
                    dgvPlanList.DataSource = planList;
                    
                    // 隐藏不需要显示的列
                    if (dgvPlanList.Columns.Contains("createName"))
                    {
                        dgvPlanList.Columns["createName"].Visible = false;
                    }
                    if (dgvPlanList.Columns.Contains("createDate"))
                    {
                        dgvPlanList.Columns["createDate"].Visible = false;
                    }
                    if (dgvPlanList.Columns.Contains("productId"))
                    {
                        dgvPlanList.Columns["productId"].Visible = false;
                    }
                    if (dgvPlanList.Columns.Contains("state"))
                    {
                        dgvPlanList.Columns["state"].Visible = false;
                    }
                    if (dgvPlanList.Columns.Contains("isDel"))
                    {
                        dgvPlanList.Columns["isDel"].Visible = false;
                    }
                    
                    // 添加分解按钮列
                    AddDecomposeButtonColumn();
                   
                  
                    totalCount = response.totalCount;
                    totalPage = response.totalPage;

                    lblTotalCount.Text = string.Format("共{0}条", totalCount);
                    lblTotalPage.Text = string.Format("第{0}页/共{1}页", pageIndex, totalPage);

                    UpdatePagingButtons();
                  
                    // 在数据加载完成后调整列宽
                    this.BeginInvoke(new Action(() => {
                            AdjustDataGridViewColumns();
                            // 更新分解按钮状态
                            UpdateDecomposeButtons();
                        }));
                       
                    }
                    else
                    {
                       
                        
                        // 清空数据源，避免显示旧数据
                        dgvPlanList.DataSource = new List<PlanData>();
                        lblTotalCount.Text = "共0条";
                        lblTotalPage.Text = "第1页/共1页";
                        UpdatePagingButtons();
                    }
                
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询异常: {ex.Message}");
                MessageBox.Show(string.Format("查询失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                // 清空数据源，避免显示旧数据
                dgvPlanList.DataSource = new List<PlanData>();
                lblTotalCount.Text = "共0条";
                lblTotalPage.Text = "第1页/共1页";
                UpdatePagingButtons();
            }
           
            // 获取订单来源的值
            string productSource = null; // 默认设置为 null
            if (cboProductResource.SelectedValue != null)
            {
                // 只有当选中项的Value不为0（非"请选择"）时，才获取它的值
                if ((int)cboProductResource.SelectedValue != 0)
                {
                    productSource = cboProductResource.SelectedValue.ToString();
                }
            }

            // 获取状态的值
            string planstate = null; // 默认设置为 null
            if (cboProductState.SelectedValue != null)
            {
                // 只有当选中项的Value不为-1（非"请选择"）时，才获取它的值
                if ((int)cboProductState.SelectedValue != -1)
                {
                    planstate = cboProductState.SelectedValue.ToString();
                }
            }

        }
        /// <summary>
        /// 分页默认值
        /// </summary>
        private int pageIndex = 1;
        private int pageSize = 15;
        private int totalCount = 0;
        private int totalPage = 0;
        private void UpdatePagingButtons()
        {
            btnFirstPage.Enabled = pageIndex > 1;
            btnPreviousPage.Enabled = pageIndex > 1;
            btnNextPage.Enabled = pageIndex < totalPage;
            btnLastPage.Enabled = pageIndex < totalPage;
        }
        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirstPage_Click(object sender, EventArgs e)
        {
            if(pageIndex!=1)
            {
                pageIndex = 1;
                btnSearch_Click(sender, e);
            }
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPreviousPage_Click(object sender, EventArgs e)
        {
            if (pageIndex>1)
            {
                pageIndex--;
                btnSearch_Click(sender, e);
            }
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            if(pageIndex<totalPage)
            {
                pageIndex++;
                btnSearch_Click(sender, e);
            }
        }
        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLastPage_Click(object sender, EventArgs e)
        {
            if(pageIndex!=totalPage)
            {
                pageIndex=totalPage;
                btnSearch_Click(sender, e);
            }
        }
        /// <summary>
        /// 跳转页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGoPage_Click(object sender, EventArgs e)
        {
            if (int.TryParse(txtPageNumber.Text, out int pageNum) && pageNum >= 1 && pageNum <= totalPage)
            {
                pageIndex = pageNum;
                btnSearch_Click(sender, e);
            }
            else
            {
                MessageBox.Show("请输入有效的页码。");
            }
        }
        /// <summary>
        /// 查询的下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void ProductPlanMain_Load(object sender, EventArgs e)
        {
            // 设置DataGridView的滚动条
            dgvPlanList.ScrollBars = ScrollBars.Both;
            
            // 添加调试信息
            Console.WriteLine($"=== ProductPlanMain_Load ===");
            Console.WriteLine($"DataGridView ReadOnly: {dgvPlanList.ReadOnly}");
            Console.WriteLine($"DataGridView Enabled: {dgvPlanList.Enabled}");
            Console.WriteLine($"DataGridView Columns Count: {dgvPlanList.Columns.Count}");
            
            // 检查按钮列
            for (int i = 0; i < dgvPlanList.Columns.Count; i++)
            {
                var col = dgvPlanList.Columns[i];
                Console.WriteLine($"列{i}: {col.HeaderText}, 类型: {col.GetType().Name}, 可见: {col.Visible}");
            }
            
           
           
            btnSearch_Click(sender, e);
            
            // 注意：SetColumnOrder已经在btnSearch_Click中调用了，这里不需要重复调用
         
            var sourceList = new List<OrderSource>
            {
                new OrderSource { Value = 0, Name = "请选择" },
                new OrderSource { Value = 1, Name = "销售订单" },
                new OrderSource { Value = 2, Name = "库存备货" },
                new OrderSource { Value = 3, Name = "其他" }
            };
            cboProductResource.DataSource = sourceList;
            cboProductResource.DisplayMember = "Name";
            cboProductResource.ValueMember = "Value";
            cboProductResource.SelectedIndex = 0;
            int selectedValue=(int)cboProductResource.SelectedValue;

            // 为新增表单的来源类型下拉框设置选项
            var resourceList = new List<OrderSource>
            {
                new OrderSource { Value = 0, Name = "请选择来源类型" },
                new OrderSource { Value = 1, Name = "销售订单" },
                new OrderSource { Value = 2, Name = "库存备货" },
                new OrderSource { Value = 3, Name = "其他" }
            };
            cboResource.DataSource = resourceList;
            cboResource.DisplayMember = "Name";
            cboResource.ValueMember = "Value";
            cboResource.SelectedIndex = 0;

            var state = new List<PlanState>
            {
                new PlanState { Value = -1, PlanName = "请选择" },
                new PlanState { Value = 0, PlanName = "未分解" },
                new PlanState { Value = 1, PlanName = "已分解" },
               
            };
            cboProductState.DataSource = state;
            cboProductState.DisplayMember = "PlanName";
            cboProductState.ValueMember = "Value";
            cboProductState.SelectedIndex = 0; // 选择"请选择"项
            // 现在可以安全地获取SelectedValue了
            int selectedValues = (int)cboProductState.SelectedValue; // 这会是-1
            
            // 在数据加载完成后调整列宽
            this.BeginInvoke(new Action(() => {
                AdjustDataGridViewColumns();
            }));
            

            
        }


        /// <summary>
        /// 显示的来源类型列和状态列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlanList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 检查是否是来源类型列或状态列
            if (e.ColumnIndex >= 0 && e.ColumnIndex < dgvPlanList.Columns.Count)
            {
                var column = dgvPlanList.Columns[e.ColumnIndex];
                
                // 处理来源类型列
                if (column.DataPropertyName == "resource" && e.Value != null)
                {
                    // 尝试将单元格的值转换为 int
                    if (int.TryParse(e.Value.ToString(), out int resourceValue))
                    {
                        // 根据 int 值返回对应的中文文本
                        switch (resourceValue)
                        {
                            case 1:
                                e.Value = "销售订单";
                                break;
                            case 2:
                                e.Value = "库存备货";
                                break;
                            case 3:
                                e.Value = "其他";
                                break;
                            default:
                                e.Value = "未知";
                                break;
                        }

                        // 告诉事件处理程序，我们已经处理了格式化，不需要进行默认的格式化操作
                        e.FormattingApplied = true;
                    }
                }
                
                // 处理状态列
                if (column.DataPropertyName == "planState" && e.Value != null)
                {
                    // 尝试将单元格的值转换为 int
                    if (int.TryParse(e.Value.ToString(), out int stateValue))
                    {
                        // 根据 int 值返回对应的中文文本
                        switch (stateValue)
                        {
                            case 0:
                                e.Value = "未分解";
                                break;
                            case 1:
                                e.Value = "已分解";
                                break;
                            default:
                                e.Value = "未知";
                                break;
                        }

                        // 告诉事件处理程序，我们已经处理了格式化，不需要进行默认的格式化操作
                        e.FormattingApplied = true;
                    }
                }
            }
        }
        /// <summary>
        /// 新增产品名称后的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProductName_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建产品选择窗体
                var selectProductForm = new SelectProduct();
                if (selectProductForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果用户选择了产品，将产品信息填充到对应的输入框
                    if (selectProductForm.SelectedProduct != null)
                    {
                        var product = selectProductForm.SelectedProduct;
                        txtproname.Text = product.ProductName; // 成品名称
                        txtspecifi.Text = product.Specification; // 规格型号
                        txtunit.Text = product.UnitName; // 单位
                        txtProcode.Text = product.ProductCode; // 成品编号
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("打开产品选择窗口失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增订单编号后的按钮
        /// </summary>
        private void btnOrderNumber_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建销售订单选择窗体
                var selectSaleForm = new SelectSale();
                if (selectSaleForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果用户选择了销售订单，将订单信息填充到对应的输入框
                    if (selectSaleForm.SelectedSale != null)
                    {
                        var sale = selectSaleForm.SelectedSale;
                        txtOrderCode.Text = sale.SalesOrderId.ToString(); // 订单编号显示销售单Id
                      
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("打开销售订单选择窗口失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增计划
        /// </summary>
        private async void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtPlanCode.Text))
                {
                    MessageBox.Show("请输入计划编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPlanCode.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtPlanName.Text))
                {
                    MessageBox.Show("请输入计划名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPlanName.Focus();
                    return;
                }

                // 创建PlanData对象
                var planData = new PlanData
                {
                    planCode = txtPlanCode.Text.Trim(),
                    planName = txtPlanName.Text.Trim(),
                    resource = 1, // 默认来源类型为销售订单
                    productName = txtproname.Text.Trim(),
                    productCode = txtProcode.Text.Trim(),
                    specification = txtspecifi.Text.Trim(),
                    unitName = txtunit.Text.Trim(),
                    planNum = int.TryParse(txtPlannum.Text, out int planNum) ? planNum : 0,
                    planStart = DateTime.TryParse(dtpStart.Text, out DateTime startDate) ? startDate : (DateTime?)null,
                    planEnd = DateTime.TryParse(dtpComple.Text, out DateTime endDate) ? endDate : (DateTime?)null,
                    requireDate = DateTime.TryParse(dtpRequireDate.Text, out DateTime reqDate) ? reqDate : (DateTime?)null,
                    planState = 1, // 默认状态
                    createName = "张三", 
                    createDate = DateTime.Now,
                    productId = 0, // 可以从产品选择中获取
                    state =1,
                    salesOrderId = int.TryParse(txtOrderCode.Text, out int orderId) ? orderId : 0 // 从销售订单选择中获取
                };

                // 发送POST请求到后端API
                var apiResponse = await ApiRequestHelper.PostAsync<AddPlanApiResponse>("api/Plan/AddPlan", planData);
                
                if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                {
                    ApiRequestHelper.ShowSuccess("生产计划添加成功！");
                    // 清空表单
                    ClearForm();
                    // 刷新列表
                    Console.WriteLine("新增成功，开始刷新生产计划数据...");
                    btnSearch_Click(null, null);
                    Console.WriteLine("生产计划数据刷新完成");

                    // 基于新增的生产计划，同步生成一条生产工单
                    try
                    {
                        await CreateProductionOrderFromPlanAsync(planData);
                    }
                    catch (Exception exGen)
                    {
                        // 不中断主流程，仅提示
                        Console.WriteLine($"根据生产计划生成生产工单失败: {exGen.Message}");
                        ApiRequestHelper.ShowWarning($"生产工单生成失败: {exGen.Message}");
                    }
                }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"添加失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    ApiRequestHelper.ShowError(errorMsg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("添加生产计划失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 清空新增表单
        /// </summary>
        private void ClearForm()
        {
         
            txtPlanCode.Text = string.Empty;
            txtPlanName.Text = string.Empty;
            txtproname.Text = string.Empty;
            txtProcode.Text = string.Empty;
            txtspecifi.Text = string.Empty;
            txtunit.Text = string.Empty;
            txtPlannum.Text = string.Empty;
            txtOrderCode.Text = string.Empty;
            cboResource.SelectedIndex = 0; 
            dtpStart.Text = "";
            dtpComple.Text = "";
            dtpRequireDate.Text = "";
        }

        /// <summary>
        /// 刷新计划列表
        /// </summary>
        private async Task LoadPlanList()
        {
            try
            {
                // 保存当前的搜索条件
                string currentPlanCode = txtProductCode.Text.Trim();
                string currentPlanName = txtProductName.Text.Trim();
                object currentResource = cboProductResource.SelectedValue;
                object currentState = cboProductState.SelectedValue;
                
                // 调用搜索方法刷新数据
                await Task.Run(() => {
                    this.Invoke(new Action(() => {
                        btnSearch_Click(null, null);
                    }));
                });
                
                // 恢复搜索条件
                txtProductCode.Text = currentPlanCode;
                txtProductName.Text = currentPlanName;
                if (currentResource != null) cboProductResource.SelectedValue = currentResource;
                if (currentState != null) cboProductState.SelectedValue = currentState;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"刷新计划列表失败: {ex.Message}");
                MessageBox.Show($"刷新数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 强制刷新生产计划数据（用于BOM分解后）
        /// </summary>
        private async Task RefreshPlanDataAsync()
        {
            try
            {
                Console.WriteLine("=== 开始强制刷新生产计划数据 ===");
                
                // 保存当前的搜索条件
                string currentPlanCode = txtProductCode.Text.Trim();
                string currentPlanName = txtProductName.Text.Trim();
                object currentResource = cboProductResource.SelectedValue;
                object currentState = cboProductState.SelectedValue;
                
                // 清空搜索条件，获取所有数据
                txtProductCode.Text = "";
                txtProductName.Text = "";
                cboProductResource.SelectedIndex = -1;
                cboProductState.SelectedIndex = -1;
                
                // 调用搜索方法刷新数据
                await Task.Run(() => {
                    this.Invoke(new Action(() => {
                        btnSearch_Click(null, null);
                    }));
                });
                
                // 恢复搜索条件
                txtProductCode.Text = currentPlanCode;
                txtProductName.Text = currentPlanName;
                if (currentResource != null) cboProductResource.SelectedValue = currentResource;
                if (currentState != null) cboProductState.SelectedValue = currentState;
                
                Console.WriteLine("=== 强制刷新生产计划数据完成 ===");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"强制刷新生产计划数据失败: {ex.Message}");
                MessageBox.Show($"刷新数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除生产计划
        /// </summary>
        /// <param name="planId">计划ID</param>
        /// <param name="planCode">计划编号</param>
        private async Task DeletePlanAsync(int planId, string planCode)
        {
            try
            {
                Console.WriteLine($"=== 开始删除生产计划 ===");
                Console.WriteLine($"DeletePlanAsync被调用，参数: planId={planId}, planCode={planCode}");
                Console.WriteLine($"计划ID: {planId}");
                Console.WriteLine($"计划编号: {planCode}");
                
                // 构建删除请求参数
                var deleteData = new { planId = planId };
                
                // 调用删除API
                var apiResponse = await ApiRequestHelper.PostAsync<ApiResponse>("api/Plan/DelPlan", deleteData);
                
                if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                {
                    ApiRequestHelper.ShowSuccess($"生产计划 {planCode} 删除成功！");
                    
                    // 刷新列表
                    Console.WriteLine("删除成功，开始刷新生产计划数据...");
                    btnSearch_Click(null, null);
                    Console.WriteLine("生产计划数据刷新完成");
                }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"删除失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    ApiRequestHelper.ShowError(errorMsg);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除生产计划异常: {ex.Message}");
                MessageBox.Show($"删除生产计划失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 根据新增的生产计划生成一条生产工单
        /// </summary>
        private async Task CreateProductionOrderFromPlanAsync(PlanData plan)
        {
            if (plan == null) return;

            // 生成工单编号：按 GDBH#### 递增；若无法获取历史编号，则回退为时间戳
            string nextCode = await GetNextProductionOrderCodeAsync();
            if (string.IsNullOrWhiteSpace(nextCode))
            {
                nextCode = "GDBH" + DateTime.Now.ToString("MMddHHmm");
            }

            string ResourceToText(int resource)
            {
                switch (resource)
                {
                    case 1: return "销售订单";
                    case 2: return "库存备货";
                    case 3: return "其他";
                    default: return "其他";
                }
            }

            var payload = new
            {
                // 基本字段
                ProductionOrdersCode = nextCode,
                ProductionOrdersName = "新产品工单",
                ProductionOrdersProgress = 0,
                AssociatePlans = plan.planName ?? string.Empty,
                PlanNumber = plan.planCode ?? string.Empty,
                Type = ResourceToText(plan.resource),
                ProductName = plan.productName ?? string.Empty,
                ProductCode = plan.productCode ?? string.Empty,
                SpecificationModel = plan.specification ?? string.Empty,
                ProductType = "成品",
                Unit = plan.unitName ?? string.Empty,
                BOM = "BOM" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                Version = "1.1",
                PlannedQuantity = plan.planNum,
                ActualQuantity = 0,
                PlanStart = plan.planStart?.ToString("yyyy-MM-ddTHH:mm:ss"),
                PlanEnd = plan.planEnd?.ToString("yyyy-MM-ddTHH:mm:ss"),
                DemandDate = plan.requireDate?.ToString("yyyy-MM-ddTHH:mm:ss"),
                Batch = DateTime.Now.ToString("yyyyMMddHHmmss"),
                ActualStart = (string)null,
                ActualEnd = (string)null,
                Remark = "生产工单生成",
                State = 0,
                CreateBy = !string.IsNullOrWhiteSpace(Environment.UserName) ? Environment.UserName : "System"
            };

            var json = JsonConvert.SerializeObject(payload);
            using (var http = new HttpClient())
            {
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var resp = await http.PostAsync(urls+"/api/ProductionOrders/AddProductionOrdersCommand", content);
                var txt = await resp.Content.ReadAsStringAsync();
                if (!resp.IsSuccessStatusCode)
                {
                    throw new Exception($"HTTP {resp.StatusCode}: {txt}");
                }
            }
        }

        /// <summary>
        /// 从后端获取最新的工单编号并计算下一个编号（GDBH####）
        /// </summary>
        private async Task<string> GetNextProductionOrderCodeAsync()
        {
            try
            {
                using (var http = new HttpClient())
                {
                    // 取较大的 PageSize 以便尽可能拿到最新的编号
                    var url = urls+"/api/ProductionOrders/ProductionOrdersCommand?PageIndex=1&PageSize=200";
                    var resp = await http.GetAsync(url);
                    resp.EnsureSuccessStatusCode();
                    var json = await resp.Content.ReadAsStringAsync();
                    dynamic root = JsonConvert.DeserializeObject(json);
                    var arr = root?.data?.pageDatas ?? root?.data?.data;
                    int maxNo = 0;
                    if (arr != null)
                    {
                        foreach (var it in arr)
                        {
                            string code = (string)(it["productionOrdersCode"] ?? it["ProductionOrdersCode"]);
                            if (string.IsNullOrWhiteSpace(code)) continue;
                            if (code.StartsWith("GDBH", StringComparison.OrdinalIgnoreCase))
                            {
                                var numPart = new string(code.Skip(4).Where(char.IsDigit).ToArray());
                                if (int.TryParse(numPart, out int n))
                                {
                                    if (n > maxNo) maxNo = n;
                                }
                            }
                        }
                    }
                    int next = maxNo + 1;
                    return $"GDBH{next:0000}";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取下一个工单编号失败: {ex.Message}");
                return null;
            }
        }
        /// <summary>
        /// 处理DataGridView单元格点击事件
        /// </summary>
        private async void dgvPlanList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                // 添加调试信息
                Console.WriteLine($"=== CellClick事件被触发 ===");
                Console.WriteLine($"CellClick: Row={e.RowIndex}, Column={e.ColumnIndex}, ColumnName={dgvPlanList.Columns[e.ColumnIndex].HeaderText}");
                Console.WriteLine($"Column Type: {dgvPlanList.Columns[e.ColumnIndex].GetType().Name}");
                Console.WriteLine($"Is Button Column: {dgvPlanList.Columns[e.ColumnIndex] is DataGridViewButtonColumn}");
                
                // 简单测试：无论点击哪里都输出
                Console.WriteLine($"点击了第{e.RowIndex}行，第{e.ColumnIndex}列");
                
                // 检查是否点击了按钮列
                if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && e.ColumnIndex < dgvPlanList.Columns.Count)
                {
                    var column = dgvPlanList.Columns[e.ColumnIndex];
                    Console.WriteLine($"点击的列: {column.HeaderText}, 列类型: {column.GetType().Name}");
                    if (column is DataGridViewButtonColumn)
                    {
                        // 获取当前行的数据
                        var currentRow = dgvPlanList.Rows[e.RowIndex];
                        
                        // 调试：输出当前行的所有数据
                        Console.WriteLine("当前行数据:");
                        for (int i = 0; i < currentRow.Cells.Count; i++)
                        {
                            var cell = currentRow.Cells[i];
                            var col = dgvPlanList.Columns[i];
                            Console.WriteLine($"  列{i}: {col.HeaderText} = {cell.Value} (类型: {cell.Value?.GetType().Name ?? "null"})");
                        }
                        
                        if (column.HeaderText == "修改")
                        {
                            // 从DataSource获取完整的PlanData对象
                            PlanData planData = null;
                            if (dgvPlanList.DataSource is List<PlanData> planList && e.RowIndex < planList.Count)
                            {
                                planData = planList[e.RowIndex];
                                Console.WriteLine($"从DataSource获取PlanData: planId={planData.planId}, salesOrderId={planData.salesOrderId}");
                            }
                            else
                            {
                                // 如果无法从DataSource获取，则使用更安全的方式从DataGridView获取数据
                                planData = new PlanData();
                                
                                // 使用DataPropertyName来获取数据，避免硬编码列索引
                                foreach (DataGridViewColumn col in dgvPlanList.Columns)
                                {
                                    if (!string.IsNullOrEmpty(col.DataPropertyName))
                                    {
                                        var cellValue = currentRow.Cells[col.Index].Value;
                                        if (cellValue != null)
                                        {
                                            try
                                            {
                                                switch (col.DataPropertyName.ToLower())
                                                {
                                                    case "planid":
                                                        planData.planId = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "plancode":
                                                        planData.planCode = cellValue.ToString();
                                                        break;
                                                    case "planname":
                                                        planData.planName = cellValue.ToString();
                                                        break;
                                                    case "resource":
                                                        planData.resource = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "productname":
                                                        planData.productName = cellValue.ToString();
                                                        break;
                                                    case "productcode":
                                                        planData.productCode = cellValue.ToString();
                                                        break;
                                                    case "specification":
                                                        planData.specification = cellValue.ToString();
                                                        break;
                                                    case "unitname":
                                                        planData.unitName = cellValue.ToString();
                                                        break;
                                                    case "plannum":
                                                        planData.planNum = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "planstart":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime start))
                                                            planData.planStart = start;
                                                        break;
                                                    case "planend":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime end))
                                                            planData.planEnd = end;
                                                        break;
                                                    case "requiredate":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime require))
                                                            planData.requireDate = require;
                                                        break;
                                                    case "planstate":
                                                        planData.planState = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "salesorderid":
                                                        if (int.TryParse(cellValue.ToString(), out int orderId))
                                                            planData.salesOrderId = orderId;
                                                        break;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine($"转换列 {col.DataPropertyName} 的值时出错: {ex.Message}");
                                            }
                                        }
                                    }
                                }
                                
                                // 设置默认值
                                planData.createName = "张三";
                                planData.createDate = DateTime.Now;
                                planData.productId = 0;
                                planData.state = 1;
                            }

                            // 打开修改窗体
                            var updateForm = new UpdateProductPlan(planData);
                            if (updateForm.ShowDialog() == DialogResult.OK)
                            {
                                // 修改成功后直接调用搜索方法刷新数据
                                Console.WriteLine("修改成功，开始刷新生产计划数据...");
                                btnSearch_Click(null, null);
                                Console.WriteLine("生产计划数据刷新完成");
                            }
                        }
                        else if (column.HeaderText == "删除")
                        {
                            Console.WriteLine("=== 删除按钮被点击 ===");
                            // 获取计划ID
                            int planId = 0;
                            if (dgvPlanList.DataSource is List<PlanData> dataSourceList && e.RowIndex < dataSourceList.Count)
                            {
                                planId = dataSourceList[e.RowIndex].planId;
                            }
                            else
                            {
                                // 尝试从第一列获取planId
                                var planIdCell = currentRow.Cells[0];
                                if (planIdCell.Value != null && int.TryParse(planIdCell.Value.ToString(), out int id))
                                {
                                    planId = id;
                                }
                            }
                            
                            Console.WriteLine($"获取到的planId: {planId}");
                            if (planId > 0)
                            {
                                // 获取计划编号用于显示
                                string planCode = "";
                                if (dgvPlanList.DataSource is List<PlanData> dataSourceList2 && e.RowIndex < dataSourceList2.Count)
                                {
                                    planCode = dataSourceList2[e.RowIndex].planCode;
                                }
                                else
                                {
                                    // 尝试从planCode列获取
                                    foreach (DataGridViewColumn col in dgvPlanList.Columns)
                                    {
                                        if (col.DataPropertyName?.ToLower() == "plancode")
                                        {
                                            planCode = currentRow.Cells[col.Index].Value?.ToString() ?? "";
                                            break;
                                        }
                                    }
                                }
                                
                                Console.WriteLine($"计划编号: {planCode}");
                                // 确认删除
                                var result = MessageBox.Show($"确定要删除计划编号为 {planCode} 的生产计划吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                                if (result == DialogResult.Yes)
                                {
                                    // 执行删除操作
                                    await DeletePlanAsync(planId, planCode);
                                }
                            }
                            else
                            {
                                MessageBox.Show("无法获取计划ID，删除操作失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else if (column.HeaderText == "分解")
                        {
                            // 获取当前行的计划数据
                            PlanData planData = null;
                            if (dgvPlanList.DataSource is List<PlanData> planList && e.RowIndex < planList.Count)
                            {
                                planData = planList[e.RowIndex];
                            }
                            else
                            {
                                // 如果无法从DataSource获取，则从DataGridView获取数据
                                planData = new PlanData();
                                
                                foreach (DataGridViewColumn col in dgvPlanList.Columns)
                                {
                                    if (!string.IsNullOrEmpty(col.DataPropertyName))
                                    {
                                        var cellValue = currentRow.Cells[col.Index].Value;
                                        if (cellValue != null)
                                        {
                                            try
                                            {
                                                switch (col.DataPropertyName.ToLower())
                                                {
                                                    case "planid":
                                                        planData.planId = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "plancode":
                                                        planData.planCode = cellValue.ToString();
                                                        break;
                                                    case "planname":
                                                        planData.planName = cellValue.ToString();
                                                        break;
                                                    case "resource":
                                                        planData.resource = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "productname":
                                                        planData.productName = cellValue.ToString();
                                                        break;
                                                    case "productcode":
                                                        planData.productCode = cellValue.ToString();
                                                        break;
                                                    case "specification":
                                                        planData.specification = cellValue.ToString();
                                                        break;
                                                    case "unitname":
                                                        planData.unitName = cellValue.ToString();
                                                        break;
                                                    case "plannum":
                                                        planData.planNum = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "planstart":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime start))
                                                            planData.planStart = start;
                                                        break;
                                                    case "planend":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime end))
                                                            planData.planEnd = end;
                                                        break;
                                                    case "requiredate":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime require))
                                                            planData.requireDate = require;
                                                        break;
                                                    case "planstate":
                                                        planData.planState = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "salesorderid":
                                                        if (int.TryParse(cellValue.ToString(), out int orderId))
                                                            planData.salesOrderId = orderId;
                                                        break;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine($"转换列 {col.DataPropertyName} 的值时出错: {ex.Message}");
                                            }
                                        }
                                    }
                                }
                                
                                // 设置默认值
                                planData.createName = "张三";
                                planData.createDate = DateTime.Now;
                                planData.productId = 0;
                                planData.state = 1;
                            }

                            // 检查状态是否为未分解
                            if (planData.planState == 0)
                            {
                                // 打开BOM管理窗体，传递生产计划数据
                                var bomForm = new BOMForm(planData);
                                var result = bomForm.ShowDialog();
                                
                                // 分解完成后刷新列表
                                if (result == DialogResult.OK || bomForm.IsDecomposed)
                                {
                                    Console.WriteLine("BOM分解完成，开始刷新生产计划数据...");
                                    
                                    // 延迟一下再刷新，确保后端数据已更新
                                    await Task.Delay(1000);
                                    
                                    // 强制刷新数据
                                    await RefreshPlanDataAsync();
                                    
                                    Console.WriteLine("生产计划数据刷新完成");
                                }
                            }
                            else
                            {
                                MessageBox.Show("该生产计划已经分解完成，无需重复分解。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        else if(column.HeaderText=="详情")
                        {
                            PlanData planData = null;
                            if (dgvPlanList.DataSource is List<PlanData> planList && e.RowIndex < planList.Count)
                            {
                                planData = planList[e.RowIndex];
                                Console.WriteLine($"从DataSource获取PlanData详情: planId={planData.planId}, planName={planData.planName}");
                            }
                            else
                            {
                                // 如果无法从DataSource获取，则使用更安全的方式从DataGridView获取数据
                                planData = new PlanData();
                                
                                // 使用DataPropertyName来获取数据，避免硬编码列索引
                                foreach (DataGridViewColumn col in dgvPlanList.Columns)
                                {
                                    if (!string.IsNullOrEmpty(col.DataPropertyName))
                                    {
                                        var cellValue = currentRow.Cells[col.Index].Value;
                                        if (cellValue != null)
                                        {
                                            try
                                            {
                                                switch (col.DataPropertyName.ToLower())
                                                {
                                                    case "planid":
                                                        planData.planId = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "plancode":
                                                        planData.planCode = cellValue.ToString();
                                                        break;
                                                    case "planname":
                                                        planData.planName = cellValue.ToString();
                                                        break;
                                                    case "resource":
                                                        planData.resource = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "productname":
                                                        planData.productName = cellValue.ToString();
                                                        break;
                                                    case "productcode":
                                                        planData.productCode = cellValue.ToString();
                                                        break;
                                                    case "specification":
                                                        planData.specification = cellValue.ToString();
                                                        break;
                                                    case "unitname":
                                                        planData.unitName = cellValue.ToString();
                                                        break;
                                                    case "plannum":
                                                        planData.planNum = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "planstart":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime start))
                                                            planData.planStart = start;
                                                        break;
                                                    case "planend":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime end))
                                                            planData.planEnd = end;
                                                        break;
                                                    case "requiredate":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime require))
                                                            planData.requireDate = require;
                                                        break;
                                                    case "planstate":
                                                        planData.planState = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "salesorderid":
                                                        if (int.TryParse(cellValue.ToString(), out int orderId))
                                                            planData.salesOrderId = orderId;
                                                        break;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine($"转换列 {col.DataPropertyName} 的值时出错: {ex.Message}");
                                            }
                                        }
                                    }
                                }
                                
                                // 设置默认值
                                planData.createName = "张三";
                                planData.createDate = DateTime.Now;
                                planData.productId = 0;
                                planData.state = 1;
                                
                                Console.WriteLine($"从DataGridView获取PlanData详情: planId={planData.planId}, planName={planData.planName}");
                            }
                            
                            // 输出传递给详情窗体的完整数据
                            Console.WriteLine("=== 传递给ProductDetailMain的数据 ===");
                            Console.WriteLine($"计划ID: {planData.planId}");
                            Console.WriteLine($"计划编号: {planData.planCode}");
                            Console.WriteLine($"计划名称: {planData.planName}");
                            Console.WriteLine($"来源类型: {planData.resource}");
                            Console.WriteLine($"产品名称: {planData.productName}");
                            Console.WriteLine($"产品编号: {planData.productCode}");
                            Console.WriteLine($"规格型号: {planData.specification}");
                            Console.WriteLine($"计划数量: {planData.planNum}");
                            Console.WriteLine($"单位: {planData.unitName}");
                            Console.WriteLine($"计划开工时间: {planData.planStart}");
                            Console.WriteLine($"计划完工时间: {planData.planEnd}");
                            Console.WriteLine($"需求日期: {planData.requireDate}");
                            Console.WriteLine($"销售订单ID: {planData.salesOrderId}");
                            Console.WriteLine("=== 数据传递完成 ===");
                            
                            // 打开详情窗体
                            var detailForm = new ProductDetailMain(planData);
                            detailForm.ShowDialog();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CellClick异常: {ex.Message}");
                MessageBox.Show(string.Format("操作失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
       

      

        /// <summary>
        /// 添加分解按钮列
        /// </summary>
        private void AddDecomposeButtonColumn()
        {
            // 检查是否已经存在分解列
            if (dgvPlanList.Columns.Contains("DecomposeColumn"))
            {
                return;
            }

            // 创建分解按钮列
            var decomposeColumn = new DataGridViewButtonColumn();
            decomposeColumn.Name = "DecomposeColumn";
            decomposeColumn.HeaderText = "分解";
            decomposeColumn.Text = "分解";
            decomposeColumn.UseColumnTextForButtonValue = true;
            decomposeColumn.Width = 60;
            decomposeColumn.FlatStyle = FlatStyle.Flat;

            // 将分解列插入到状态列之后
            int insertIndex = -1;
            for (int i = 0; i < dgvPlanList.Columns.Count; i++)
            {
                if (dgvPlanList.Columns[i].DataPropertyName == "planState")
                {
                    insertIndex = i + 1;
                    break;
                }
            }

            if (insertIndex >= 0)
            {
                dgvPlanList.Columns.Insert(insertIndex, decomposeColumn);
            }
            else
            {
                // 如果找不到状态列，则添加到末尾
                dgvPlanList.Columns.Add(decomposeColumn);
            }

            // 为每一行设置分解按钮的显示状态
            UpdateDecomposeButtons();
        }

        /// <summary>
        /// 更新分解按钮的显示状态
        /// </summary>
        private void UpdateDecomposeButtons()
        {
            if (dgvPlanList.DataSource is List<PlanData> planList)
            {
                for (int i = 0; i < dgvPlanList.Rows.Count; i++)
                {
                    if (i < planList.Count)
                    {
                        var plan = planList[i];
                        var decomposeCell = dgvPlanList.Rows[i].Cells["DecomposeColumn"];
                        
                        // 根据状态决定是否显示分解按钮
                        if (plan.planState == 0) // 未分解
                        {
                            decomposeCell.Value = "分解";
                            decomposeCell.Style.BackColor = Color.LightGreen;
                            decomposeCell.Style.ForeColor = Color.Black;
                        }
                        else // 已分解
                        {
                            decomposeCell.Value = "";
                            decomposeCell.Style.BackColor = Color.LightGray;
                            decomposeCell.Style.ForeColor = Color.Gray;
                        }
                    }
                }
            }
        }

      

        private void dgvPlanList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                Console.WriteLine($"=== CellContentClick事件被触发 ===");
                Console.WriteLine($"CellContentClick: Row={e.RowIndex}, Column={e.ColumnIndex}, ColumnName={dgvPlanList.Columns[e.ColumnIndex].HeaderText}");
                Console.WriteLine($"Column Type: {dgvPlanList.Columns[e.ColumnIndex].GetType().Name}");
                Console.WriteLine($"Is Button Column: {dgvPlanList.Columns[e.ColumnIndex] is DataGridViewButtonColumn}");
                
                // 简单测试：无论点击哪里都输出
                Console.WriteLine($"CellContentClick: 点击了第{e.RowIndex}行，第{e.ColumnIndex}列");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CellContentClick异常: {ex.Message}");
            }
        }
    }
}
